#include "util.h"

uint8_t Add8_check(uint8_t *puch_msg, uint16_t data_len)
{
    uint8_t check_num = 0;
    for (uint16_t i = 0; i < data_len - 1; i++) {
        check_num += puch_msg[i];
    }
    return check_num;
}

uint16_t ModBus_CRC16(uint8_t *puch_msg, uint16_t data_len)
{
    uint16_t crc = 0xffff, modbus_crc = 0;
    for (uint16_t num = 0; num < data_len; num++) {
        crc = (*puch_msg++) ^ crc;
        for (uint16_t x = 0; x < 8; x++) {
            if (crc & 0x0001) {
                crc = crc >> 1;
                crc = crc ^ 0xA001;
            } else {
                crc = crc >> 1;
            }
        }
    }
    modbus_crc |= ((crc & 0x00ff) << 8);
    modbus_crc |= ((crc & 0xff00) >> 8);
    return modbus_crc;
}